package com.example.server.impl;

import com.example.dao.deptMapper.DeptMapper;
import com.example.dao.menuMapper.MenuMapper;
import com.example.dao.roleMapper.RoleMapper;
import com.example.dao.userMapper.UserMapper;
import com.example.dto.dept.Dept;
import com.example.dto.menu.Menu;
import com.example.dto.role.Role;
import com.example.dto.role.RoleCriteria;
import com.example.dto.user.User;
import com.example.exception.BadRequestException;
import com.example.exception.EntityExistException;
import com.example.server.RoleServer;
import com.example.util.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class RoleServerImpl implements RoleServer {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private DeptMapper deptMapper;

    private static final String ENTITY_NAME = "role";

    /**
     * 添加角色
     *
     * @param role
     * @return
     */
    @Override
    public void create(Role resources) {
        if (roleMapper.findByName(resources.getName()) != null) {
            throw new EntityExistException(Role.class, "username", resources.getName());
        }
        roleMapper.creat(resources);
        Role role = roleMapper.findByNames(resources.getName());
        roleMapper.adds(role,resources.getDepts());
    }

    /**
     * 删除角色
     *
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        roleMapper.dele(ids);
        roleMapper.deleteAllByIdIn(ids);
    }

    /**
     * 修改角色信息
     *
     * @param role
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Role resources) {
        Role role = roleMapper.findById(resources.getId());
        role.setDepts(deptMapper.findByIDs(role.getId()));
        System.out.println(role);
        roleMapper.del(role);
        roleMapper.add(resources, resources.getDepts());
        ValidationUtil.isNull(role.getId(), "Role", "id", resources.getId());
        role.setName(resources.getName());
        role.setDescription(resources.getDescription());
        role.setDataScope(resources.getDataScope());
        role.setDepts(resources.getDepts());
        role.setLevel(resources.getLevel());
        roleMapper.save(role, role.getDepts());
    }

    /**
     * 查找所有数据
     *
     * @return
     */
    @Override
    public List<Role> findAll() {
        List<Role> SS = roleMapper.findAllRole();
        SS.forEach(x -> {
            Long roleId = x.getId();
            List<Menu> menus = menuMapper.findByID(x.getId());
            x.setMenus(menus);
            List<Dept> dept = deptMapper.findByIDs(roleId);
            dept.forEach(l -> {
                l.setLabel(l.getName());
            });
            x.setDepts(dept);
        });
        return SS;
    }

    /**
     * 查找角色
     *
     * @param roleCriteria
     * @return
     */
    @Override
    public Map<String, Object> list(RoleCriteria roleCriteria) {
        Map<String, Object> result = new HashMap<>(4);

        Map<String, Object> wide = new HashMap<>();
        wide.put("createTime", null);
        wide.put("updateTime", null);
        wide.put("blurry", roleCriteria.getBlurry());
        wide.put("page", roleCriteria.getPage());
        wide.put("size", roleCriteria.getSize());

        List<Role> roles = roleMapper.selectList(wide);
        roles.forEach(x -> {
            Long roleId = x.getId();
            List<Menu> menus = menuMapper.findByID(x.getId());
            x.setMenus(menus);
            List<Dept> dept = deptMapper.findByIDs(roleId);
            dept.forEach(l -> {
                l.setLabel(l.getName());
            });
            x.setDepts(dept);
        });
        int count = roleMapper.findCount(wide);
        result.put("content", roles);
        result.put("totalElements", count);
        return result;
    }

    @Override
    public List<Role> findByUsersId(Long userId) {
        return new ArrayList<>(roleMapper.findByUserId(userId));
    }

    @Override
    public void verification(Set<Long> ids) {
        if (userMapper.countByRoles(ids) > 0) {
            throw new BadRequestException("所选角色存在用户关联，请解除关联再试！");
        }
    }

    @Override
    public Role findById(Long id) {
        Role role = roleMapper.findByIds(id);
        ValidationUtil.isNull(role.getId(), "Role", "id", id);
        return role;
    }

    @Override
    public void updateMenu(Role resources, Role role) {

        List<User> users = userMapper.findByRoleId(role.getId());
        // 更新菜单
        role.setMenus(resources.getMenus());
        roleMapper.save(role,role.getDepts());
    }


}
